<?php
namespace app\common\model;

use app\extra\BaseModel;
use app\extra\DBCont;
use think\Exception;

class Member extends BaseModel
{
    protected $auto = [];
    protected $insert = ['wechat_id', 'bill', 'amount'];
    public function getTeamIdAttr($value){
        if (empty($value)){
            return null;
        }
        return [
            'key' => $value,
            'value' => model('Team')->where('id', $value)->value('title')
        ];
    }
    public function setImageAttr($value){
        return serializeByArray($value, ',');
    }
    public function getImageAttr($value){
        if (empty($value)){
            return null;
        }
        return [
            'key' => $value,
            'value' => showFileUrl($value)
        ];
    }
    /**
     * 添加额外参数
     * @param $item
     */
    public function setAddedField(&$item){
        //$item['pay_info'] = '';
        $team_id = $this->where('id', $item['id'])->value('team_id');
        $match_id = model('Team')->where('id', '=', $team_id)->value('match_id');
        $is_fees = model('Match')->where('id', '=', $match_id)->value('is_fees');
        if ($is_fees == DBCont::CHARGE){
            if($item['pay_state'] == DBCont::SUCCESS) {
                $item['status_desc'] = DBCont::getPayWay($item['way']);
            } else {
                $item['status_desc'] = DBCont::getPayStatus($item['pay_state']);
            }
        } else {
            $item['status_desc'] = DBCont::getPayWay(DBCont::FREE);
        }
    }
    public function setWechatIdAttr($value=null){
        return getPersonId();
    }
    public function setBillAttr($value=null){
        do{
            $bill = getOrderNumber();
            $one = $this->where('bill', $bill)->find();
        }while(!empty($one));
        return $bill;
    }
    public function setAmountAttr($value, $data){
        $match_id = model('Team')->where('id', $data['team_id'])->value('match_id');
        if (empty($match_id)){
            return 0;
        }
        $amount = (float)model('Match')->where('id', $match_id)->value('cost', 0);
        return $amount;
    }

    /**
     * 新增个人赛
     * @param $data
     * @return BaseModel|bool
     * @throws \think\exception\PDOException
     */
    public function addTeam($data){
        $where = [
            ['id', '=', $data['match_id']],
            ['status', '=', DBCont::SUCCESS],
        ];
        $match = model('Match')->where($where)->find();
        if (empty($match) || $match->isEmpty()){
            $this->error = '比赛未开始，不能报名';
            return false;
        }
        $team = [
            'title' => $data['name'],
            'type' => DBCont::PERSON,
            'cover' => $data['image'],
            'desc' => $data['desc'],
            'match_id' => $data['match_id'],
            'cate_id' => $data['cate_id'],
        ];
        if ($match['is_fees'] == DBCont::CHARGE) {
            $data['status'] = DBCont::WAIT;
        } else {
            $data['status'] = DBCont::SUCCESS;
        }
        $TM = model('Team');
        try {
            $TM->startTrans();
            $validate = Validate('Team');
            if (!$validate->check($team)) {
                \exception($validate->getError());
            }
            $r = $TM->createAdd($team);
            if ($r === false){
                \exception($TM->getError());
            }
            $r = $this->addMember($data, $r['id'], DBCont::ROLE_CAP);
            if ($r === false){
                \exception($this->error);
            }
            $TM->commit();
            return $r;
        } catch (\Exception $e){
            $TM->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
    public function addMember($data, $team_id){
        $data['team_id'] = $team_id;
        if ($this->where('team_id', $team_id)->value('id')){
            $data['role'] = DBCont::ROLE_GENERAL;
        } else {
            $data['role'] = DBCont::ROLE_CAP;
        }
        $match_id = model('Team')->where('id', $team_id)->value('match_id');
        $is_fees = model('Match')->where('id', $match_id)->value('is_fees');
        if ($is_fees == DBCont::CHARGE) {
            $data['pay_state'] = DBCont::WAIT;
            $data['way'] = DBCont::WECHAT;
        } else {
            $data['pay_state'] = DBCont::SUCCESS;
            $data['way'] = DBCont::FREE;
        }
        $data['status'] = DBCont::WAIT;
        $validate = Validate('Member');
        if (!$validate->check($data)) {
            $this->error = $validate->getError();
            return false;
        }
        return $this->createAdd($data);
    }
    public function createAdd($data = [], $field = null, $replace = false)
    {
        $match_id = model("Team")->where('id', $data['team_id'])->value('match_id');
        if (empty($match_id)){
            $this->error = '该赛事不存在！';
            return false;
        }
        $where = [
            ['id', '=', $match_id],
            ['status', '=', DBCont::SUCCESS],
            ['start_time', '<', time()],
            ['end_time', '>', time()],
        ];
        if (empty(model('Match')->where($where)->value('id'))){
            $this->error = '该赛事或活动是非进行中，请联系管理员';
            return false;
        }
        $team_id = model('Team')->where('match_id', $match_id)->column('id');
        if (empty($team_id)){
            $this->error = '团队不存在';
            return false;
        }
        $data1 = model('member')->whereIn('team_id', $team_id)
            ->where('card', '=', $data['card'])
            ->where('pay_state', '=', DBCont::SUCCESS)
            ->select();
        if (!empty($data1) && !$data1->isEmpty()){
            $this->error = '该身份证已经参加本次赛事，请勿重新提交！';
            return false;
        }
        return parent::createAdd($data, true, $replace);
    }
}